package com.cloudfun.campusshare.service.handler;

import com.cloudfun.campuscontract.RemoteTradeInfoChainService;
import com.cloudfun.campuscontract.dto.TradeInfoDTO;
import com.cloudfun.campusshare.common.constant.BaseConstant;
import com.cloudfun.campusshare.common.model.dto.kjt.KjtNotifyBaseDTO;
import com.cloudfun.campusshare.common.model.dto.kjt.KjtPaymentNotifyDTO;
import com.cloudfun.campusshare.service.DeviceOrderService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 处理支付结果通知
 * Created by Huqin on 2020/8/17
 */
@Component
public class KjtTradeStatusHandler implements KjtNotifyHandler<KjtPaymentNotifyDTO> {

    @Autowired
    private DeviceOrderService deviceOrderService;

    @Reference(timeout = 10_000)
    private RemoteTradeInfoChainService remoteTradeInfoChainService;

    @Override
    public String notifyType() {
        return "trade_status_sync";
    }

    @Override
    public Class<KjtPaymentNotifyDTO> notifyMessageType() {
        return KjtPaymentNotifyDTO.class;
    }

    @Override
    public boolean handle(KjtNotifyBaseDTO notifyMsg) {
        KjtPaymentNotifyDTO notifyDTO = (KjtPaymentNotifyDTO) notifyMsg;
        this.payTradeResInfoUpload2BlockChain(notifyDTO);
        return deviceOrderService.paymentNotify(notifyDTO);
    }

    /**
     * 支付数据上链
     *
     * @param notifyDTO
     */
    private void payTradeResInfoUpload2BlockChain(KjtPaymentNotifyDTO notifyDTO) {
        BaseConstant.SCHEDULED_EXECUTOR.execute(() -> {
            TradeInfoDTO tradeInfoDTO = new TradeInfoDTO();
            BeanUtils.copyProperties(notifyDTO, tradeInfoDTO);
            tradeInfoDTO.setOrderNo(notifyDTO.getOuterTradeNo());
            tradeInfoDTO.setOuterTradeNo(notifyDTO.getInnerTradeNo());
            remoteTradeInfoChainService.modify(tradeInfoDTO);
        });
    }
}
